<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" :width="600" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>

<script lang="ts">
  export default defineComponent({
    name: 'ControlRuleFormModal',
  });
</script>

<script lang="ts" setup>
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm, FormSchema } from '/@/components/Form';
  import {
    saveControlRule,
    getControlRuleById,
    ControlRuleType,
    ControlRuleMode,
    SaveControlRuleParam,
  } from '/@/api/tb/controlRule';
  import { useMessage } from '/@/hooks/web/useMessage';

  // IP地址格式校验正则
  const IP_REGEX = /^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;

  const emit = defineEmits(['success', 'register']);

  const { showMessage } = useMessage();
  const isUpdate = ref(false);
  const recordData = ref<any>(null);

  const formSchema: FormSchema[] = [
    {
      field: 'type',
      label: '规则类型',
      component: 'Select',
      required: true,
      componentProps: {
        placeholder: '请选择规则类型',
        options: [
          {
            label: '设备ID',
            value: ControlRuleType.DEVICE_ID,
          },
          {
            label: 'IP地址',
            value: ControlRuleType.DEVICE_IP,
          },
        ],
      },
    },
    {
      field: 'value',
      label: '规则内容',
      component: 'Input',
      required: true,
      componentProps: {
        placeholder: '请输入规则内容',
      },
      helpMessage: '设备ID类型请输入设备ID，IP类型请输入IP地址（例如：192.168.1.100）',
      rules: [
        {
          required: true,
          message: '请输入规则内容',
        },
        {
          validator: async (_rule, value) => {
            if (!value) {
              return Promise.resolve();
            }
            const formValues = await getFieldsValue();
            if (formValues.type === ControlRuleType.DEVICE_IP) {
              if (!IP_REGEX.test(value)) {
                return Promise.reject('请输入有效的IP地址格式（例如：192.168.1.100）');
              }
            }
            return Promise.resolve();
          },
          trigger: 'change',
        },
      ],
    },
    {
      field: 'mode',
      label: '控制模式',
      component: 'Select',
      required: true,
      componentProps: {
        placeholder: '请选择控制模式',
        options: [
          {
            label: '黑名单',
            value: ControlRuleMode.BLACKLIST,
          },
          {
            label: '白名单',
            value: ControlRuleMode.WHITELIST,
          },
        ],
      },
    },
    {
      field: 'description',
      label: '描述',
      component: 'InputTextArea',
      componentProps: {
        placeholder: '请输入规则描述',
        rows: 3,
      },
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate, updateSchema, getFieldsValue }] = useForm({
    labelWidth: 100,
    schemas: formSchema,
    showActionButtonGroup: false,
    baseColProps: { span: 24 },
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    resetFields();
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.id;

    if (unref(isUpdate)) {
      try {
        const ruleData = await getControlRuleById(data.id.id);
        recordData.value = ruleData;

        // 编辑时禁用规则类型和控制模式字段
        updateSchema({
          field: 'type',
          componentProps: {
            disabled: true,
          },
        });
        updateSchema({
          field: 'mode',
          componentProps: {
            disabled: true,
          },
        });

        setFieldsValue({
          type: ruleData.type,
          value: ruleData.value,
          mode: ruleData.mode,
          description: ruleData.description,
        });
      } catch (error) {
        console.error('获取规则详情失败:', error);
      }
    } else {
      recordData.value = null;

      // 新增时，设置默认值
      const defaultValues: any = {};

      if (data?.defaultType) {
        defaultValues.type = data.defaultType;
        // 禁用类型字段
        updateSchema({
          field: 'type',
          componentProps: {
            disabled: true,
          },
        });
      } else {
        // 确保类型字段可编辑
        updateSchema({
          field: 'type',
          componentProps: {
            disabled: false,
          },
        });
      }

      if (data?.defaultMode) {
        defaultValues.mode = data.defaultMode;
        // 禁用模式字段
        updateSchema({
          field: 'mode',
          componentProps: {
            disabled: true,
          },
        });
      } else {
        // 确保模式字段可编辑
        updateSchema({
          field: 'mode',
          componentProps: {
            disabled: false,
          },
        });
      }

      if (Object.keys(defaultValues).length > 0) {
        setFieldsValue(defaultValues);
      }
    }
  });

  const getTitle = computed(() => (!unref(isUpdate) ? '新增规则' : '编辑规则'));

  async function handleSubmit() {
    try {
      const values = await validate();
      setModalProps({ confirmLoading: true });

      const submitData: any = {
        type: values.type,
        value: values.value,
        mode: values.mode,
        description: values.description,
      };

      if (unref(isUpdate) && recordData.value?.id) {
        // 更新时使用列表传入的id对象中的id字符串
        submitData.id = recordData.value.id;
      }

      await saveControlRule(submitData);
      showMessage(unref(isUpdate) ? '更新规则成功！' : '创建规则成功！');
      closeModal();
      emit('success');
    } catch (error) {
      console.error('保存规则失败:', error);
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
